package com.tpod.taxi.view.adapter;

import java.util.ArrayList;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.tpod.taxi.R;
import com.tpod.taxi.entity.Taxi;
import com.tpod.taxi.utils.UIUtils;

public class ListTaxiAdapter extends BaseAdapter {

	public ArrayList<Taxi> taxies = new ArrayList<Taxi>();
	private LayoutInflater inflater = LayoutInflater.from(UIUtils.context);
	private CallClickListener listener;

	@Override
	public int getCount() {
		return taxies.size();
	}

	@Override
	public Taxi getItem(int arg0) {
		return taxies.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	public String getTelNumbber(int pos) {
		return taxies.get(pos).getPhone();
	}

	@Override
	public View getView(int pos, View view, ViewGroup vgroup) {
		ViewHolder holder;
		// if (view == null) {
		view = inflater.inflate(R.layout.list_row_item, vgroup, false);
		holder = new ViewHolder(view);
		// } else {
		// holder = (ViewHolder) view.getTag();
		// }

		Taxi data = taxies.get(pos);
		holder.name.setText(data.getName());

		holder.number.setText(data.getPhone());
		if (data.haveFourSeater() && data.haveSevenSeater()) {
			holder.seater.setText(UIUtils.getRes().getString(
					R.string.fourAndSevenSeater));
		} else if (data.haveFourSeater()) {
			holder.seater.setText(UIUtils.getRes().getString(
					R.string.fourSeater));
		} else {
			holder.seater.setText(UIUtils.getRes().getString(
					R.string.sevenSeater));
		}
		holder.btnCall.setTag(pos);
		if (listener != null) {
			holder.btnCall.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					int pos = Integer.parseInt(arg0.getTag().toString());
					listener.onCallClick(arg0, pos, getTelNumbber(pos));
				}
			});
		}

		return view;
	}

	static class ViewHolder {

		public TextView name;
		public TextView number;
		public TextView seater;
		public Button btnCall;

		public ViewHolder(View root) {
			root.setLayoutParams(new AbsListView.LayoutParams(
					AbsListView.LayoutParams.MATCH_PARENT, UIUtils.getRes()
							.getDimensionPixelSize(R.dimen.list_item_height)));

			name = (TextView) root.findViewById(R.id.list_item_tv_name);
			number = (TextView) root
					.findViewById(R.id.list_item_tv_tel_nummber);
			seater = (TextView) root.findViewById(R.id.list_item_tv_seater);
			btnCall = (Button) root.findViewById(R.id.list_item_call_button);
		}
	}

	public void setCallClickListener(CallClickListener listener) {
		this.listener = listener;
	}

	public interface CallClickListener {
		void onCallClick(View v, int pos, String nummber);
	}
}
